﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ByrForumAPI
{
    public class OAuth
    {
        private const string AUTHORIZE_URL = "https://api.weibo.com/oauth2/authorize";
        private const string ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";

        private const string BASIC_URL = "http://api.byr.cn";

        /// <summary>
        /// 获取App Key
        /// </summary>
        public string AppKey
        {
            get;
            internal set;
        }

        public string UserId
        {
            get;
            internal set;
        }

        public string Password
        {
            get;
            internal set;
        }

        /// <summary>
        /// 代理设置
        /// </summary>
        public WebProxy Proxy
        {
            get;
            set;
        }

        // default
        public OAuth()
        {
            this.AppKey = "78e223c052793f0b";
            this.UserId = "guest";
            this.Password = string.Empty;
        }
       
        public OAuth(string userId, string password)
        {
            this.AppKey = "78e223c052793f0b";
            this.UserId = userId;
            this.Password = password;
        }

        public string Request(string url)
        {
            // build request url
            string rawUrl = string.Format("{0}{1}?appkey={2}", BASIC_URL, url, this.AppKey);
            
            UriBuilder uri = new UriBuilder(rawUrl);
            string result = string.Empty;

            HttpWebRequest http = WebRequest.Create(uri.Uri) as HttpWebRequest;
            http.ServicePoint.Expect100Continue = false;
            http.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
            if (Proxy != null)
            {

                if (Proxy.Credentials != null)
                {
                    http.UseDefaultCredentials = true;
                }
                http.Proxy = Proxy;
            }
            
            http.Credentials = new NetworkCredential(this.UserId, this.Password);

            http.Method = "GET";

            using (WebResponse response = http.GetResponse())
            {

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    try
                    {
                        result = reader.ReadToEnd();
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
            }
            return result;
        }

    }
}
